import time

from selenium import webdriver
from selenium.common.exceptions import WebDriverException, InvalidArgumentException, NoSuchElementException
from selenium.webdriver.common.by import By


class Base:
    """
    封装了selenium基础方法,给case继承使用
    """

    def __init__(self, browser):
        # 打开浏览器
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'ie':
            self.driver = webdriver.Ie()
        else:
            print('不支持该浏览器')

    def get(self, url):
        # 请求网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的网址不正确')

    def find_element(self, locator):
        # 定位元素
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素定位失败,无法点击')

    def get_attribute(self, locator):
        # 获取元素属性
        element = self.find_element(locator)
        if element is not None:
            print(element.get_attribute('outerHTML'))
        else:
            print('元素定位失败,无法获取属性')

    def back(self):
        # 浏览器后退
        self.driver.back()

    def forward(self):
        # 浏览器前进
        self.driver.forward()

    def refresh(self):
        # 浏览器刷新
        self.driver.refresh()

    def quit(self, seconds=0):
        # 退出浏览器
        time.sleep(seconds)
        self.driver.quit()
